//
//  ViewController.m
//  XMBasePj
//
//  Created by 王猛 on 16/3/2.
//  Copyright © 2016年 WXIAOM. All rights reserved.
//

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>
@property (nonatomic,strong) CLLocationManager *locationManager;
@property (nonatomic,strong) UIButton *locBtn;
@end

@implementation ViewController
- (UIButton *)locBtn{
    if (!_locBtn) {
        _locBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 150, 40)];
        [_locBtn setTitleColor:[UIColor blackColor] forState:0];
        [_locBtn setTitle:@"位置" forState:0];
    }
    return _locBtn;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor greenColor];
    [self setNavigation];
    [self locationUserPlace];
}
- (void)setNavigation{
    self.title = @"首页";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.locBtn];
}
//定位
- (void)locationUserPlace {
    // 1. 实例化定位管理器
    _locationManager = [[CLLocationManager alloc] init];
    [_locationManager requestWhenInUseAuthorization];
    // 2. 设置代理
    _locationManager.delegate = self;
    // 3. 定位精度
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    // 4.请求用户权限：分为：?只在前台开启定位?在后台也可定位，
    //注意：建议只请求?和?中的一个，如果两个权限都需要，只请求?即可，
    //??这样的顺序，将导致bug：第一次启动程序后，系统将只请求?的权限，?的权限系统不会请求，只会在下一次启动应用时请求?
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
        //[_locationManager requestWhenInUseAuthorization];//?只在前台开启定位
        [_locationManager requestAlwaysAuthorization];//?在后台也可定位
    }
    // 5.iOS9新特性：将允许出现这种场景：同一app中多个location manager：一些只能在前台定位，另一些可在后台定位（并可随时禁止其后台定位）。
//    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
//       _locationManager.allowsBackgroundLocationUpdates = YES;
//    }
    // 6. 更新用户位置
    [_locationManager startUpdatingLocation];
}

//追踪到位置
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    //反地址编码
    CLLocation *location = [locations firstObject];
    //停止定位
    [manager stopUpdatingLocation];
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *placemark = placemarks[0];
        NSString *cityName = [[placemark.locality stringByAppendingString:placemark.subLocality] stringByAppendingString:placemark.thoroughfare];
        NSLog(@"%@",placemark);
        [self.locBtn setTitle:cityName  forState:UIControlStateNormal];
        NSLog(@"%@",cityName);
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
